Entrega grupal

Eli, Jazmín, Flor, Shengnan, Mariajo

Paquetes necesarios

Insertad aquí todos los paquetes vayáis necesitando

Code
rm(list = ls())
library(tidyverse)
library(glue)
library(forcats)
library(lubridate)
library(waffle)

Entrega grupal

Datos

La práctica se basará en los archivos de datos electorales que se indican a continuación, recopilando datos sobre las elecciones al Congreso de los Diputados en España desde 2008 hasta la actualidad, así como encuestas, códigos de municipios y abreviaturas

Code
# NO TOQUES NADA
election_data <- read_csv(file = "./data/datos_elecciones_brutos.csv")
cod_mun <- read_csv(file = "./data/cod_mun.csv")
surveys <- read_csv(file = "./data/historical_surveys.csv")
abbrev <- read_csv(file = "./data/siglas.csv")

Datos

  • election_data: archivo con las elecciones al congreso
  • cod_mun: archivo con los códigos y nombres de cada municipio
  • abbrev: siglas de cada partido
  • surveys: encuestas electorales desde 1982.

Datos

  • surveys: encuestas electorales desde 1982.
    • type_survey: tipo de encuesta (nacional, regional…)
    • date_elec: fecha de las futuras elecciones
    • id_pollster, pollster, media: id y nombre de la empresa encuestadora, así como medio que la encargó
    • field_date_from, field_date_to: fechas de inicio y fin del trabajo de la encuesta
    • exit_poll: ¿es una encuesta a pie de urna?
    • size: tamaño muestral de la encuesta
    • turnout: participación (estimación)

Objetivos

El objetivo de la entrega es realizar un análisis de los datos electorales, llevando a cabo la depuración, los resúmenes y los gráficos que consideres necesarios, tanto de los resultados como de la precisión de las encuestas electorales.

En concreto, debes trabajar únicamente en el período de tiempo que incluye las elecciones desde 2008 hasta las últimas elecciones de 2019

Ítems obligatorios

  1. Los datos deben ser convertidos a tidydata donde sea apropiado.

  2. Debes incluir al menos un join entre tablas.

  3. Los paquetes {glue}, {forcats} y {lubridate} deben ser utilizados en algún punto

  4. Los siguientes elementos deben usarse al menos una vez: mutate, summarise, group_by (o su equivalente), case_when

  5. Deberéis definir al menos una función (con más de 5 líneas de código)

Ítems obligatorios

  1. Contamos con muchos partidos que se presentan a las elecciones. Solo nos interesarán los siguientes partidos (cuidado: algunos tienen o tenían federaciones - sucursales - con otros nombres):
  • PARTIDO SOCIALISTA OBRERO ESPAÑOL
  • PARTIDO POPULAR
  • CIUDADANOS
  • PARTIDO NACIONALISTA VASCO
  • BLOQUE NACIONALISTA GALLEGO
  • UNIDAS PODEMOS - IU (Unidas Podemos, Unidos Podemos, Podemos, IU, Podem, y Ezker Batua).
  • ESQUERRA REPUBLICANA DE CATALUNYA
  • EH - BILDU (ahora son una coalición de partidos formada por lo que antes era Sortu, Eusko Alkartasuna, Aralar, Alternatiba).
  • VOX

Ítems obligatorios

  1. Todo lo que no esté en alguno de los anteriores partidos debe ser correctamente reagrupado (y resumido) en OTROS

  2. Las siglas deben ser usadas en las visualizaciones (ideas en https://r-graph-gallery.com/).

  3. Debes usar todos los archivos en algún momento.

  4. Debes descartar las encuestas que:

-   se refieran a elecciones anteriores a 2008
-   sean a pie de urna
-   tamaño muestral desconocido o inferior a 500.
-   tenga 1 día o menos de trabajo de campo.

Depuración de datos

Code
names(election_data)
  [1] "tipo_eleccion"                                                                         
  [2] "anno"                                                                                  
  [3] "mes"                                                                                   
  [4] "vuelta"                                                                                
  [5] "codigo_ccaa"                                                                           
  [6] "codigo_provincia"                                                                      
  [7] "codigo_municipio"                                                                      
  [8] "codigo_distrito_electoral"                                                             
  [9] "numero_mesas"                                                                          
 [10] "censo"                                                                                 
 [11] "participacion_1"                                                                       
 [12] "participacion_2"                                                                       
 [13] "votos_blancos"                                                                         
 [14] "votos_nulos"                                                                           
 [15] "votos_candidaturas"                                                                    
 [16] "BERDEAK-LOS VERDES"                                                                    
 [17] "ARALAR"                                                                                
 [18] "PARTIDO OBRERO SOCIALISTA INTERNACIONALISTA"                                           
 [19] "ALTERNATIVA MOTOR Y DEPORTES"                                                          
 [20] "PARTIDO HUMANISTA"                                                                     
 [21] "PARTIDO POPULAR"                                                                       
 [22] "EZKER BATUA-BERDEAK-ALTERNATIVA"                                                       
 [23] "EUSKO ALKARTASUNA"                                                                     
 [24] "PARTIDO ANTITAURINO CONTRA EL MALTRATO ANIMAL"                                         
 [25] "UNION PROGRESO Y DEMOCRACIA"                                                           
 [26] "PARTIDO SOCIALISTA DE EUSKADI-EUSKADIKO EZKERRA"                                       
 [27] "POR UN MUNDO MAS JUSTO"                                                                
 [28] "EUZKO ALDERDI JELTZALEA-PARTIDO NACIONALISTA VASCO"                                    
 [29] "CIUDADANOS-PARTIDO DE LA CIUDADANIA"                                                   
 [30] "PARTIDO CARLISTA DE EUSKALHERRIA-EUSKALHERRIKO KARLISTA ALDERDIA"                      
 [31] "PARTIDO COMUNISTA DE LOS PUEBLOS DE ESPAÑA"                                            
 [32] "DEMOCRACIA NACIONAL"                                                                   
 [33] "ALIANZA NACIONAL"                                                                      
 [34] "FALANGE ESPAÑOLA DE LAS JONS"                                                          
 [35] "ALTERNATIVA ESPAÑOLA"                                                                  
 [36] "IZQUIERDA UNIDA-ALTERNATIVA"                                                           
 [37] "PARTIDO SOCIAL DEMOCRATA"                                                              
 [38] "PARTIDO FAMILIA Y VIDA"                                                                
 [39] "PARTIDO SOCIALISTA OBRERO ESPAÑOL"                                                     
 [40] "CIUDADANOS EN BLANCO"                                                                  
 [41] "ESPAÑA 2000"                                                                           
 [42] "TIERRA COMUNERA"                                                                       
 [43] "FALANGE AUTENTICA"                                                                     
 [44] "FALANGE ESPAÑOLA DE LA JONS"                                                           
 [45] "ESQUERRA UNIDA DEL PAIS VALENCIA-IZQUIERDA REPUBLICANA: ESQUERRA UNIDA I REPUBLICANA"  
 [46] "BLOC-INICIATIVA-VERDS"                                                                 
 [47] "CENTRO DEMOCRATICO LIBERAL"                                                            
 [48] "REPRESENTACION CANNABICA NAVARRA"                                                      
 [49] "PARTIT ANTITAURI CONTRA EL MALTRACTAMENT ANIMAL"                                       
 [50] "LOS VERDES-GRUPO VERDE"                                                                
 [51] "LOS VERDES-ELS VERDS"                                                                  
 [52] "ESQUERRA REPUBLICANA DEL PAIS VALENCIA-PAIS VALENCIA SI"                               
 [53] "FAMILIA Y VIDA"                                                                        
 [54] "CIUDADANOS PARTIDO DE LA CIUDADANIA"                                                   
 [55] "COALICIO VALENCIANA"                                                                   
 [56] "PARTIDO CENTRISTAS"                                                                    
 [57] "OPCIO NACIONALISTA VALENCIANA"                                                         
 [58] "PER LA REPUBLICA VALENCIANA"                                                           
 [59] "COALICION ANDALUCISTA"                                                                 
 [60] "PARTIDO DE ALMERIA"                                                                    
 [61] "IZQUIERDA UNIDA LOS VERDES-CONVOCATORIA POR ANDALUCIA - ALTERNATIVA"                   
 [62] "LOS VERDES"                                                                            
 [63] "CENTRO DEMOCRATICO Y SOCIAL"                                                           
 [64] "PARTIDO COMUNISTA DEL PUEBLO CASTELLANO"                                               
 [65] "LOS VERDES DE EUROPA"                                                                  
 [66] "FALANGE ESPAÑOLA DE LAS J.O.N.S."                                                      
 [67] "CENTRO DEMOCRATICO ESPAÑOL"                                                            
 [68] "FRENTE ESPAÑOL"                                                                        
 [69] "COMUNION TRADICIONALISTA CARLISTA"                                                     
 [70] "EXTREMADURA UNIDA"                                                                     
 [71] "ESPAÑA-2000"                                                                           
 [72] "ESQUERRA UNIDA - ELS VERDS"                                                            
 [73] "UNITAT PER LES ILLES"                                                                  
 [74] "COALICIO TREBALLADORS PER LA DEMOCRACIA"                                               
 [75] "PARTIT ILLENC DE SES ILLES BALEARS"                                                    
 [76] "ALIANÇA BALEAR"                                                                        
 [77] "PARTIT PER CATALUNYA"                                                                  
 [78] "PARTIT OBRER SOCIALISTA INTERNACIONALISTA"                                             
 [79] "CONVERGENCIA I UNIO"                                                                   
 [80] "PARTIDO DE LAS LIBERTADES CIVILES"                                                     
 [81] "PARTIT POPULAR/PARTIDO POPULAR"                                                        
 [82] "PARTIDO DE LOS PENSIONISTAS EN ACCION"                                                 
 [83] "PARTIT FAMILIA I VIDA"                                                                 
 [84] "PARTIT DELS SOCIALISTES DE CATALUNYA"                                                  
 [85] "LLUITA INTERNACIONALISTA"                                                              
 [86] "PARTIT CARLI DE CATALUNYA"                                                             
 [87] "ESQUERRA REPUBLICANA DE CATALUNYA"                                                     
 [88] "PARTIDO COMUNISTA DEL PUEBLO DE CATALUNYA"                                             
 [89] "ELS VERDS-LOS VERDES"                                                                  
 [90] "PARTIT REPUBLICA CATALA"                                                               
 [91] "INICIATIVA PER CATALUNYA VERDS-ESQUERRA UNIDA I ALTERNATIVA"                           
 [92] "ELS VERDS - L'ALTERNATIVA ECOLOGISTA"                                                  
 [93] "CIUTADANS-PARTIDO DE LA CIUDADANIA"                                                    
 [94] "EI ESCONS INSUBMISOS-ALTERNATIVA DELS DEMOCRATES DESCONTENTS"                          
 [95] "IZQUIERDA REPUBLICANA-PARTIT REPUBLICA D'ESQUERRA"                                     
 [96] "SOLIDARIDAD Y AUTOGESTION INTERNACIONALISTA"                                           
 [97] "PARTIT HUMANISTA DE CATALUNYA"                                                         
 [98] "AGRUPACION CIUDADANA"                                                                  
 [99] "PARTIDO COMUNISTA DEL PUEBLO CASTELLANO-PCPE"                                          
[100] "INICIATIVA CIUDADANA BURGALESA"                                                        
[101] "ALIANZA POR BURGOS"                                                                    
[102] "PARTIDO CARLISTA"                                                                      
[103] "INICIATIVA MERINDADES DE CASTILLA"                                                     
[104] "LOS VERDES DE EXTREMADURA"                                                             
[105] "PARTIDO POSITIVISTA CRISTIANO"                                                         
[106] "ESQUERRA REPUBLICANA DEL PAIS VALENCIA-PAIS VALENCIA, SI"                              
[107] "PARTIT COMUNISTA DELS POBLES D'ESPANYA"                                                
[108] "IDENTITAT REGNE DE VALENCIA"                                                           
[109] "UNIDAD CASTELLANA"                                                                     
[110] "IZQUIERDA UNIDA LOS VERDES CONVOCATORIA POR ANDALUCIA-ALTERNATIVA"                     
[111] "PARTIDO DOS SOCIALISTAS DE GALICIA-PARTIDO SOCIALISTA OBRERO ESPAÑOL"                  
[112] "ESQUERDA UNIDA-IZQUIERDA UNIDA-ALTERNATIVA"                                            
[113] "BLOQUE NACIONALISTA GALEGO"                                                            
[114] "ASAMBLEA DE VOTACION ELECTRONICA"                                                      
[115] "INDEPENDIENTES POR CUENCA"                                                             
[116] "ESCONS INSUBMISOS-ALTERNATIVA DELS DEMOCRATES DESCONTENTS"                             
[117] "ELS VERDS-ALTERNATIVA VERDA"                                                           
[118] "PARTIT HUMANISTA"                                                                      
[119] "PARTIT COMUNISTA DEL POBLE DE CATALUNYA"                                               
[120] "FAMILIA I VIDA"                                                                        
[121] "IZQUIERDA UNIDA LOS VERDES-CONVOCATORIA POR ANDALUCIA-ALTERNATIVA"                     
[122] "PARTIDO REGIONALISTA DE GUADALAJARA"                                                   
[123] "PARTIDO POLITICO ARALAR"                                                               
[124] "PARTIDO SOCIALISTA DE EUSKADI-EUSKADIKO EZKERRA (PSOE)"                                
[125] "UNION CENTRISTA LIBERAL"                                                               
[126] "CHUNTA ARAGONESISTA"                                                                   
[127] "PARTIDO ARAGONES"                                                                      
[128] "PARTIDO SOCIAL DEMOCRATA-FEDERACION DE LOS INDEPENDIENTES DE ARAGON"                   
[129] "PARTIDO CIUDADANOS UNIDOS DE ARAGON"                                                   
[130] "PARTIDO SOCIALISTA OBRERO ESPAÑOL DE ANDALUCIA"                                        
[131] "UNION DEL PUEBLO LEONES"                                                               
[132] "PARTIDO UNIONISTA ESTADO DE ESPAÑA"                                                    
[133] "GENTES DE EL BIERZO"                                                                   
[134] "PARTIDO REGIONALISTA DEL PAIS LEONES"                                                  
[135] "ESCONS INSUBMISOS ALTERNATIVA DELS DEMOCRATES DESCONTENTS"                             
[136] "INICIATIVA PER CATALUNYA VERDS - ESQUERRA UNIDA I ALTERNATIVA"                         
[137] "PARTIDO RIOJANO"                                                                       
[138] "ALTERNATIVA EN BLANCO"                                                                 
[139] "PARTIDO COMUNISTA DO POVO GALEGO"                                                      
[140] "PARTIDO DOS SOCIALISTAS DE GALICIA-PSOE"                                               
[141] "IZQUIERDA UNIDA COMUNIDAD DE MADRID-ALTERNATIVA"                                       
[142] "PARTIDO DE LOS NO-FUMADORES"                                                           
[143] "LOS VERDES COMUNIDAD DE MADRID-LOS VERDES DE EUROPA"                                   
[144] "PARTIDO LIBERTADES CIVILES"                                                            
[145] "PARTIDO DE ALIANZA IBEROAMERICANA EUROPEA"                                             
[146] "CENTRO DEMOCRATICO SOCIAL"                                                             
[147] "PARTIDO LIBERAL DEL EMPLEO Y LA VIVIENDA ESTATAL"                                      
[148] "UNION POR LEGANES"                                                                     
[149] "PARTIDO SOLIDARIDAD Y AUTOGESTION INTERNACIONALISTA"                                   
[150] "LUCHA INTERNACIONALISTA"                                                               
[151] "IZQUIERDA UNIDA DE LA REGION DE MURCIA-ALTERNATIVA"                                    
[152] "UNION DEL PUEBLO NAVARRO EN COALICION CON EL PARTIDO POPULAR"                          
[153] "NAFARROA BAI"                                                                          
[154] "IZQUIERDA UNIDA DE NAVARRA - NAFARROAKO EZKER BATUA - ALTERNATIVA"                     
[155] "PARTIDO COMUNISTA DE LOS PUEBLOS DE ESPAÑA-EUSKAL KOMUNISTAK"                          
[156] "PARTIDO COMUNISTA DO POBO GALEGO"                                                      
[157] "UNION, PROGRESO Y DEMOCRACIA"                                                          
[158] "IZQUIERDA UNIDA - BLOQUE POR ASTURIES - LOS VERDES"                                    
[159] "ANDECHA ASTUR"                                                                         
[160] "CONVERGENCIA DEMOCRATICA ASTURIANA"                                                    
[161] "IZQUIERDA REPUBLICANA"                                                                 
[162] "UNIDA"                                                                                 
[163] "MOVIMIENTO FALANGISTA DE ESPAÑA"                                                       
[164] "IZQUIERDA UNIDA CANARIA-ALTERNATIVA"                                                   
[165] "COALICION CANARIA-PARTIDO NACIONALISTA CANARIO-PARTIDO DE INDEPENDIENTES DE LANZAROTE" 
[166] "PARTIDO COMUNISTA DEL PUEBLO CANARIO"                                                  
[167] "UNIDAD DEL PUEBLO"                                                                     
[168] "MOVIMIENTO POR LA UNIDAD DEL PUEBLO CANARIO"                                           
[169] "ALTERNATIVA NACIONALISTA CANARIA"                                                      
[170] "NUEVA CANARIAS-CENTRO CANARIO"                                                         
[171] "OS VERDES - GRUPO VERDE"                                                               
[172] "PARTIDO POR UN MUNDO MAS JUSTO"                                                        
[173] "PARTIDO ALTERNATIVA MOTOR Y DEPORTES"                                                  
[174] "UNION CIUDADANA PROGRESISTAS INDEPENDIENTES DE CANARIAS"                               
[175] "COALICION CANARIA-PARTIDO NACIONALISTA CANARIO"                                        
[176] "PARTIDO COMUNISTA PUEBLOS DE ESPAÑA"                                                   
[177] "ALTERNATIVA MOTOR Y DEPORTE"                                                           
[178] "PARTIDO POPULAR/PARTIT POPULAR"                                                        
[179] "PARTIDO IZQUIERDA REPUBLICANA-PARTIT REPUBLICA D'ESQUERRA"                             
[180] "NOSALTRES SOM"                                                                         
[181] "PARTIDO COMUNISTA DEL PUEBLO DE CATALUÑA"                                              
[182] "PARTIDO CENTRISTA"                                                                     
[183] "ESQUERRA UNIDA DEL PAIS VALENCIA-IZQUIERDA REPUBLICANA:ESQUERRA UNIDA I REPUBLICANA"   
[184] "UNIDAD REGIONALISTA DE CASTILLA Y LEON"                                                
[185] "PARTIDO CARLISTA DE EUSKALERRIA-PARTIDO CARLISTA"                                      
[186] "IZQUIERDA UNIDA DE CEUTA"                                                              
[187] "BIDEZKO MUNDURANTZ/POR UN MUNDO MAS JUSTO"                                             
[188] "UNIÓN PROGRESO Y DEMOCRACIA"                                                           
[189] "EQUO"                                                                                  
[190] "PARTIDO ANIMALISTA CONTRA EL MALTRATO ANIMAL"                                          
[191] "AMAIUR"                                                                                
[192] "UNIFICACIÓN COMUNISTA DE ESPAÑA"                                                       
[193] "IZQUIERDA UNIDA-LOS VERDES: LA IZQUIERDA PLURAL/EZKER ANITZA (IU-LV)"                  
[194] "IZQUIERDA UNIDA DE CASTILLA-LA MANCHA-LOS VERDES: LA IZQUIERDA PLURAL"                 
[195] "POR UN MUNDO MÁS JUSTO"                                                                
[196] "ESCAÑOS EN BLANCO"                                                                     
[197] "FORO CENTRO Y DEMOCRACIA"                                                              
[198] "ESQUERRA UNIDA DEL PAIS VALENCIA-LOS VERDES: L'ESQUERRA PLURAL"                        
[199] "BLOC-INICIATIVA-VERDS-EQUO-COALICIÓ COMPROMÍS"                                         
[200] "ESQUERRA REPUBLICANA DEL PAÍS VALENCIÀ"                                                
[201] "REPUBLICANOS"                                                                          
[202] "ANTICAPITALISTAS"                                                                      
[203] "PARTIDO ANDALUCISTA"                                                                   
[204] "IZQUIERDA UNIDA LOS VERDES-CONVOCATORIA POR ANDALUCÍA: LA IZQUIERDA PLURAL(IULV-CA)"   
[205] "PARTIDO REGIONALISTA POR ANDALUCIA ORIENTAL"                                           
[206] "DEMOS EL CAMBIO"                                                                       
[207] "IZQUIERDA UNIDA DE CASTILLA Y LEON: LA IZQUIERDA PLURAL (IUCL)"                        
[208] "HARTOS.ORG"                                                                            
[209] "PARTIDO POPULAR-EXTREMADURA UNIDA"                                                     
[210] "IZQUIERDA UNIDA VERDES-SOCIALISTAS INDEPENDIENTES DE EXTREMADURA: LA IZQUIERDA PLURAL" 
[211] "CONVERGENCIA POR EXTREMADURA"                                                          
[212] "ESQUERRA REPUBLICANA"                                                                  
[213] "PSM-INICIATIVA VERDS-ENTESA-EQUO"                                                      
[214] "ESCONS EN BLANC"                                                                       
[215] "ESQUERRA UNIDA ILLES BALEARS: LA IZQUIERDA PLURAL"                                     
[216] "ESQUERRA REPUBLICANA DE CATALUNYA-CATALUNYA SÍ"                                        
[217] "PARTIT ANIMALISTA CONTRA EL MALTRACTAMENT ANIMAL"                                      
[218] "ANTICAPITALISTES"                                                                      
[219] "PIRATES DE CATALUNYA"                                                                  
[220] "PLATAFORMA PER CATALUNYA"                                                              
[221] "INICIATIVA PER CATALUNYA VERDS-ESQUERRA UNIDA I ALTERNATIVA: L'ESQUERRA PLURAL"        
[222] "CONVERGÈNCIA I UNIÓ"                                                                   
[223] "PARTIDO DE CASTILLA Y LEÓN"                                                            
[224] "IZQUIERDA UNIDA DE CASTILLA Y LEÓN: LA IZQUIERDA PLURAL"                               
[225] "CIUDADANOS DE CENTRO DEMOCRÁTICO"                                                      
[226] "IZQUIERDA UNIDA LOS VERDES-CONVOCATORIA POR ANDALUCÍA: LA IZQUIERDA PLURAL"            
[227] "PARTIDO DE INTERNET"                                                                   
[228] "PARTIDO PIRATA"                                                                        
[229] "ESQUERRA UNIDA PAÍS VALENCIÀ-ELS VERDS: L'ESQUERRA PLURAL"                             
[230] "CONVERXENCIA VINTEÚN"                                                                  
[231] "PARTIDO DOS SOCIALISTAS DE GALICIA - PSOE"                                             
[232] "ESQUERDA UNIDA-OS VERDES: A ESQUERDA PLURAL"                                           
[233] "PARTIDO CASTELLANO"                                                                    
[234] "CONVERGÈNCIA i UNIÓ"                                                                   
[235] "INICIATIVA PER CATALUNYA VERDS-ESQUERRA UNIDA i ALTERNATIVA: L'ESQUERRA PLURAL"        
[236] "BIDEZKO MUNDURANTZ/POR UN MUNDO MÁS JUSTO"                                             
[237] "IZQUIERDA UNIDA-LOS VERDES: LA IZQUIERDA PLURAL/EZKER ANITZA"                          
[238] "CHUNTA ARAGONESISTA-IZQUIERDA UNIDA, LA IZQUIERDA DE ARAGÓN: LA IZQUIERDA PLURAL"      
[239] "PARTIDO POPULAR EN COALICIÓN CON EL PARTIDO ARAGONÉS"                                  
[240] "PER UN MÓN MÉS JUST"                                                                   
[241] "IZQUIERDA UNIDA-LA IZQUIERDA PLURAL"                                                   
[242] "PARTIDO DOS SOCIALISTAS DE GALICIA - PARTIDO SOCIALISTA OBRERO ESPAÑOL"                
[243] "IZQUIERDA UNIDA-LOS VERDES: LA IZQUIERDA PLURAL"                                       
[244] "FORO DE CIUDADANOS"                                                                    
[245] "PARTIDO DE LA LIBERTAD INDIVIDUAL"                                                     
[246] "ACCION CIUDADANA POR MALAGA"                                                           
[247] "PARTIDO PARA LA REGENERACION DE LA DEMOCRACIA EN ESPAÑA"                               
[248] "MUERTE AL SISTEMA"                                                                     
[249] "IZQUIERDA UNIDA-VERDES DE LA REGION DE MURCIA: LA IZQUIERDA PLURAL"                    
[250] "UNIÓN DEL PUEBLO NAVARRO EN COALICIÓN CON EL PARTIDO POPULAR"                          
[251] "IZQUIERDA-EZKERRA/LA IZQUIERDA PLURAL"                                                 
[252] "GEROA BAI"                                                                             
[253] "IZQUIERDA UNIDA DE ASTURIAS-IZQUIERDA XUNIDA D'ASTURIES:LA IZQUIERDA PLURAL"           
[254] "PARTIDO DEMOCRATICO Y CONSTITUCIONAL"                                                  
[255] "COALICIÓN CANARIA-NUEVA CANARIAS"                                                      
[256] "CANARIAS VERDE Y ROJA: LA IZQUIERDA PLURAL"                                            
[257] "HIGIENE DEMOCRATICA"                                                                   
[258] "SÍ SE PUEDE, SOCIALISTAS POR TENERIFE, EQUO"                                           
[259] "IZQUIERDA UNIDA CANARIA-INICIATIVA POR EL HIERRO-LOS VERDES: LA IZQUIERDA PLURAL"      
[260] "BASTA YA, AGRUPACIÓN ABIERTA DE PARTIDOS POLÍTICOS"                                    
[261] "IZQUIERDA UNIDA DE CANTABRIA: LA IZQUIERDA PLURAL"                                     
[262] "PARTIDO REGIONALISTA DE CANTABRIA"                                                     
[263] "PARTIT REPUBLICÀ D'ESQUERRA-REPUBLICANS"                                               
[264] "SOCIALISTAS POR TERUEL"                                                                
[265] "UNION DE CIUDADANOS INDEPENDIENTES DE TOLEDO"                                          
[266] "ESCAÑOS EN BLANCO/ESCONS EN BLANC"                                                     
[267] "UNITS X VALENCIA"                                                                      
[268] "IU - LOS VERDES: LA IZQUIERDA PLURAL / EZKER ANITZA"                                   
[269] "CHUNTA ARAGONESISTA-IZQUIERDA UNIDA, La Izquierda de Aragón: La Izquierda Plural"      
[270] "COALICION CABALLAS"                                                                    
[271] "IZQUIERDA UNIDA - PARTIDO DEMOCRÁTICO Y SOCIAL DE CEUTA: LA IZQUIERDA PLURAL"          
[272] "PARTIDO SOCIALISTA DE EUSKADI-EUSKADIKO EZKERRA (P"                                    
[273] "RECORTES CERO-GRUPO VERDE"                                                             
[274] "UNIDAD POPULAR- ORAIN BATERA:EZKER ANITZA-IZQUIERD"                                    
[275] "PODEMOS-AHAL DUGU"                                                                     
[276] "ONGI ETORRI"                                                                           
[277] "CIUDADANOS-PARTIDO DE LA CIUDADANÍA"                                                   
[278] "EUSKAL HERRIA BILDU"                                                                   
[279] "ESCAÑOS EN BLANCO - AULKI ZURIAK"                                                      
[280] "LIBERTAD NAVARRA-LIBERTATE NAFARRA"                                                    
[281] "UNIDAD POPULAR: IZQUIERDA UNIDA, UNIDAD POPULAR EN"                                    
[282] "PODEMOS"                                                                               
[283] "PARTIDO LIBERAL DE DERECHAS"                                                           
[284] "VOX"                                                                                   
[285] "UNITAT POPULAR:ESQUERRA UNIDA DEL PAÍS VALENCIÀ, U"                                    
[286] "COMPROMÍS-PODEMOS-ÉS EL MOMENT"                                                        
[287] "SOM VALENCIANS"                                                                        
[288] "ARA, PAÍS VALENCIÀ"                                                                    
[289] "FORO DEMÓCRATA"                                                                        
[290] "LOS VERDES-ECOPACIFISTAS"                                                              
[291] "PARTIDO LIBERTARIO"                                                                    
[292] "UNIDAD POPULAR: IZQUIERDA UNIDA LOS VERDES-CONVOCA"                                    
[293] "CIUDADANOS PARTIDO DE LA CIUDADANÍA"                                                   
[294] "EXTREMADURA UNIDA-EXTREMEÑOS"                                                          
[295] "UNITAT POPULAR BALEARS: IZQUIERDA UNIDA, UNIDAD PO"                                    
[296] "EL PI - PROPOSTA PER LES ILLES"                                                        
[297] "MÉS"                                                                                   
[298] "UNIÓ DEMOCRÀTICA DE CATALUNYA"                                                         
[299] "CIUTADANS-PARTIDO DE LA CIUDADANÍA"                                                    
[300] "EN COMÚ PODEM"                                                                         
[301] "DEMOCRÀCIA I LLIBERTAT. CONVERGÈNCIA. DEMÒCRATES."                                     
[302] "INICIATIVA FEMINISTA"                                                                  
[303] "SOLIDARIDAD Y AUTOGESTIÓN INTERNACIONALISTA"                                           
[304] "UNIDAD POPULAR: IZQUIERDA UNIDA-UNIDAD POPULAR EN"                                     
[305] "UNITAT POPULAR: ESQUERRA UNIDA DEL PAÍS VALENCIÀ,"                                     
[306] "PARTIT COMUNISTA DELS POBLES D¿ESPANYA"                                                
[307] "PARTIDO ANIMALISTA-CONTRA EL MALTRATO ANIMAL"                                          
[308] "PARTIDO COMUNISTA OBRERO ESPAÑOL"                                                      
[309] "COMUNISTAS DA GALIZA"                                                                  
[310] "NÓS-CANDIDATURA GALEGA (BNG-CG-FOGA-PCPG-PG)"                                          
[311] "EN MAREA"                                                                              
[312] "PARTIDO ANIMALISTA CONTRA O MALTRATO ANIMAL"                                           
[313] "PARTIDO DA TERRA"                                                                      
[314] "CIUTADANS - PARTIDO DE LA CIUDADANÍA"                                                  
[315] "UNIDAD POPULAR: IZQUIERDA UNIDA LOS VERDES - CONVO"                                    
[316] "PARTIDO POPULAR (PP)"                                                                  
[317] "EUSKAL HERRIA BILDU (EH Bildu)"                                                        
[318] "CIUDADANOS-PARTIDO DE LA CIUDADANÍA (C's)"                                             
[319] "UNIDAD POPULAR-ORAIN BATERA:EZKER ANITZA-IZQUIERDA"                                    
[320] "LIBERTAD NAVARRA, LIBERTATE NAFARRA (Ln)"                                              
[321] "PARTIDO ANIMALISTA CONTRA EL MALTRATO ANIMAL (PACM"                                    
[322] "UNIÓN PROGRESO Y DEMOCRACIA (UPYD)"                                                    
[323] "CIUDADANOS, PARTIDO DE LA CIUDADANÍA"                                                  
[324] "PODEMOS-Ahora Alto Aragón en Común"                                                    
[325] "UNIDAD POPULAR EN ARAGÓN: IZQUIERDA UNIDA, CHUNTA"                                     
[326] "PARTIDO POPULAR EN COALICIÓN CON EL PARTIDO ARAGON"                                    
[327] "INDEPENDIENTES POR ARAGÓN"                                                             
[328] "CIUDADANOS LIBRES UNIDOS"                                                              
[329] "ANDALUCES DE JAÉN UNIDOS"                                                              
[330] "CIUDADANOS RURALES AGRUPADOS"                                                          
[331] "PARTIDO REGIONALISTA DEL PAÍS LEONÉS"                                                  
[332] "COMUNISTAS DA GALIZA-PCPE"                                                             
[333] "X LA IZQUIERDA-LOS VERDES"                                                             
[334] "MÁLAGA POR SÍ"                                                                         
[335] "SOLUCIONA"                                                                             
[336] "UNIDAD POPULAR: UNIDAD POPULAR EN COMÚN, IZQUIERDA"                                    
[337] "UNIÓN DEL PUEBLO NAVARRO EN COALICIÓN CON EL PARTI"                                    
[338] "UNIDAD POPULAR-ORAIN BATERA:IZQUIERDA UNIDA, BATZA"                                    
[339] "LIBERTAD NAVARRA, LIBERTATE NAFARRA"                                                   
[340] "X A ESQUERDA"                                                                          
[341] "PARTIDO POPULAR-FORO"                                                                  
[342] "UNIDAD POPULAR: IZQUIERDA UNIDA. UNIDAD POPULAR EN"                                    
[343] "CANARIAS DECIDE: LOS VERDES, UNIDAD DEL PUEBLO Y A"                                    
[344] "COALICIÓN CANARIA - PARTIDO NACIONALISTA CANARIO"                                      
[345] "PARTIDO SOCIALISTA OBRERO ESPAÑOL-NUEVA CANARIAS"                                      
[346] "COALICIÓN CANARIA-PARTIDO NACIONALISTA CANARIO"                                        
[347] "UNIDAD POPULAR: IZQUIERDA UNIDA CANARIA, UNIDAD PO"                                    
[348] "PARTIT DELS SOCIALISTES DE CATALUNYA (PSC-PSOE)"                                       
[349] "ESCONS EN BLANC/ESCAÑOS EN BLANCO"                                                     
[350] "AVANT VALENCIANS"                                                                      
[351] "EN POSITIU"                                                                            
[352] "ESCAÑOS EN BLANCO-AULKI ZURIAK"                                                        
[353] "PODEMOS/AHAL DUGU"                                                                     
[354] "EZKERRA-X LA IZQUIERDA"                                                                
[355] "JUSTIZIA SOCIAL, PARTICIPACIÓN CIUDADANA"                                              
[356] "UNIDAD POPULAR-IZQUIERDA UNIDA"                                                        
[357] "PARTIDO SOCIALISTA DE EUSKADI-EUSKADIKO EZKERRA(PSOE)"                                 
[358] "UNIDOS PODEMOS/ELKARREKIN AHAL DUGU"                                                   
[359] "UNIDOS PODEMOS"                                                                        
[360] "COMPROMÍS-PODEMOS-EUPV: A LA VALENCIANA"                                               
[361] "UNIDOS PODEMOS POR ANDALUCÍA"                                                          
[362] "IZQUIERDA ANTICAPITALISTA REVOLUCIONARIA"                                              
[363] "SOBIRANIA PER A LES ILLES"                                                             
[364] "UNITS PODEM MÉS"                                                                       
[365] "EN COMÚ PODEM-GUANYEM EL CANVI"                                                        
[366] "ESQUERRA REPUBLICANA/CATALUNYA SÍ"                                                     
[367] "CONVERGÈNCIA DEMOCRÀTICA DE CATALUNYA"                                                 
[368] "CIUTADANS, PARTIDO DE LA CIUDADANÍA"                                                   
[369] "PARTIDO SOMOS ANDALUCES POR ANDALUCÍA Y LOS PUEBLO"                                    
[370] "BNG-NÓS CANDIDATURA GALEGA"                                                            
[371] "UNIDOS PODEMOS EN ALTO ARAGÓN"                                                         
[372] "ENTABAN"                                                                               
[373] "MOVIMIENTO ARAGONÉS SOCIAL"                                                            
[374] "UNIÓN DEL PUEBLO LEONÉS"                                                               
[375] "ALIANZA DE CENTRO DEMOCRÁTICO"                                                         
[376] "HEGOALDE RIOJA-LIBERTAD NAVARRA"                                                       
[377] "LA FUERZA DE LOS MAYORES DE ESPAÑA"                                                    
[378] "UNIDOS PODEMOS-ELKARREKIN AHAL DUGU"                                                   
[379] "UNIDOS PODEMOS/XUNÍOS PODEMOS"                                                         
[380] "JUNTOS POR CANARIAS"                                                                   
[381] "ESCANOS EN BRANCO"                                                                     
[382] "UNIDOS PODEMOS EN ARAGÓN"                                                              
[383] "UNIÓN DE TODOS"                                                                        
[384] "LA FALANGE"                                                                            
[385] "RENOVACIO POLITICA"                                                                    
[386] "CIUDADANOS DE CENTRO DEMOCRÁTICO-CANDIDATURA INDEP"                                    
[387] "PARTIDO COMUNISTA DE LOS TRABAJADORES DE EUSKADI/E"                                    
[388] "ELKARREKIN PODEMOS-UNIDAS PODEMOS"                                                     
[389] "POR UN MUNDO MÁS JUSTO (BIDEZKO MUNDURANTZ)"                                           
[390] "UNIDAS PODEMOS"                                                                        
[391] "PARTIDO COMUNISTA DE LOS TRABAJADORES DE ESPAÑA"                                       
[392] "RECORTES CERO-GRUPO VERDE-PARTIDO CASTELLANO-TIERR"                                    
[393] "LOS VERDES ECOPACIFISTAS ADELANTE"                                                     
[394] "COMPROMÍS: BLOC-INICIATIVA-VERDSEQUO"                                                  
[395] "PARTIDO COMUNISTA DEL PUEBLO ANDALUZ"                                                  
[396] "ACTÚA"                                                                                 
[397] "EXTREMEÑOS PREX CREX"                                                                  
[398] "DEFENSA DE LO PÚBLICO"                                                                 
[399] "EL PI - PROPOSTA PER LES ILLES BALEARS"                                                
[400] "UNIDAS PODEMOS-UNIDES PODEM"                                                           
[401] "Veus PROGRESSISTES"                                                                    
[402] "PARTIT SOCIALISTA OBRER ESPANYOL"                                                      
[403] "IZQUIERDA EN POSITIVO"                                                                 
[404] "JUNTS PER CATALUNYA-JUNTS"                                                             
[405] "ESQUERRA REPUBLICANA DE CATALUNYA-SOBIRANISTES"                                        
[406] "POBLE LLIURE - SOM ALTERNATIVA - PIRATES DE CATALU"                                    
[407] "EN COMÚ PODEM - GUANYEM EL CANVI"                                                      
[408] "PARTIT COMUNISTA DELS TREBALLADORS DE CATALUNYA"                                       
[409] "CONVERGENTS"                                                                           
[410] "ANDALUCÍA POR SÍ"                                                                      
[411] "AVANT ADELANTE LOS VERDES"                                                             
[412] "PARTIDO DEMÓCRATA SOCIAL JUBILADOS EUROPEOS - UNID"                                    
[413] "PARTIDO COMUNISTA DOS TRABALLADORES DE GALIZA"                                         
[414] "COMPROMISO POR GALICIA"                                                                
[415] "EN COMÚN-UNIDAS PODEMOS"                                                               
[416] "PARTIDO DOS SOCIALISTAS DE GALICIA-PARTIDO SOCIALI"                                    
[417] "PARTIDO DE JUBILADOS POR EL FUTURO. DIGNIDAD Y DEM"                                    
[418] "EUSKADIKO LANGILEEN ALDERDI KOMUNISTA/PARTIDO COMU"                                    
[419] "UNIDAS PODEMOS-ALTOARAGÓN EN COMÚN"                                                    
[420] "FEDERACION DE LOS INDEPENDIENTES DE ARAGON"                                            
[421] "PUYALON"                                                                               
[422] "CIUDADANOS INDEPENDIENTES DE LINARES UNIDOS"                                           
[423] "PARTIDO REPUBLICANO INDEPENDIENTE SOLIDARIO ANDALU"                                    
[424] "PARTIT POPULAR-PARTIDO POPULAR"                                                        
[425] "CONVERXENCIA 21"                                                                       
[426] "SOMOS REGIÓN"                                                                          
[427] "DEMOCRACIA PLURAL"                                                                     
[428] "NAVARRA SUMA"                                                                          
[429] "VIVIR OURENSE"                                                                         
[430] "UNIDAS PODEMOS-XUNIES PODEMOS"                                                         
[431] "PARTIDO POPULAR - FORO"                                                                
[432] "AHORA CANARIAS: Alternativa Nacionalista Canaria A"                                    
[433] "NUEVA CANARIAS"                                                                        
[434] "FEMINISM8"                                                                             
[435] "CENTRADOS"                                                                             
[436] "PLATAFORMA DEL PUEBLO SORIANO"                                                         
[437] "SOM VALENCIANS EN MOVIMENT"                                                            
[438] "UNIÓN REGIONALISTA DE CASTILLA Y LEÓN"                                                 
[439] "PARTIDO DE ACCIÓN SOLIDARIA EUROPEA"                                                   
[440] "COALICION POR MELILLA"                                                                 
[441] "BIDEZKO MUNDURANTZ-POR UN MUNDO MÁS JUSTO"                                             
[442] "PARTIDO COMUNISTA DE LOS TRABAJADORES DE EUSKADI/EUSKADIKO LANGILEEN ALDERDI KOMUNISTA"
[443] "PARTIDO DEMÓCRATA SOCIAL JUBILADOS EUROPEOS"                                           
[444] "RECORTES CERO-GRUPO VERDE-PARTIDO CASTELLANO-TIERRA COMUNERA"                          
[445] "MÉS COMPROMÍS"                                                                         
[446] "POR ÁVILA"                                                                             
[447] "MÁS PAÍS"                                                                              
[448] "MÉS ESQUERRA"                                                                          
[449] "CANDIDATURA D'UNITAT POPULAR-PER LA RUPTURA"                                           
[450] "MÁS PAÍS-ANDALUCÍA"                                                                    
[451] "AUNA COMUNITAT VALENCIANA"                                                             
[452] "MÁS PAÍS-EQUO"                                                                         
[453] "POR UN MUNDO MÁIS XUSTO/POR UN MUNDO MÁS JUSTO"                                        
[454] "PARTIDO POPULAR / PARTIT POPULAR"                                                      
[455] "CONVERGENCIA ANDALUZA"                                                                 
[456] "EUSKADIKO LANGILEEN ALDERDI KOMUNISTA/PARTIDO COMUNISTA DE LOS TRABAJADORES DE EUSKADI"
[457] "FEDERACIÓN DE LOS INDEPENDIENTES DE ARAGÓN"                                            
[458] "PARTIDO REPUBLICANO INDEPENDIENTE SOLIDARIO ANDALUZ"                                   
[459] "CONTIGO SOMOS DEMOCRACIA"                                                              
[460] "PARTIDO COMUNISTA DE LOS TRABAJADORES DE ESPAÑA/ES"                                    
[461] "POR UN MUNDO MÁS JUSTO/BIDEZKO MUNDURANTZ"                                             
[462] "UNIDAS PODEMOS-XUNÍES PODEMOS"                                                         
[463] "AHORA CANARIAS: Alternativa Nacionalista Canaria (ANC) y Unidad del Pueblo"            
[464] "NUEVA CANARIAS-COALICIÓN CANARIA"                                                      
[465] "AGRUPACIÓN DE ELECTORES TERUEL EXISTE"                                                 
[466] "UNIDOS Actuando por la Democracia"                                                     
[467] "MÁS PAÍS-CANDIDATURA ECOLOGISTA"                                                       
[468] "MÁS PAÍS-CHUNTA ARAGONESISTA-EQUO"                                                     
[469] "MOVIMIENTO ARAGONES SOCIAL"                                                            
[470] "MOVIMIENTO POR LA DIGNIDAD Y LA CIUDADANÍA DE CEUT"                                    
[471] "COALICIÓN POR MELILLA"                                                                 
Code
#Convertir a tidy data
eleccion_tidy <- 
  election_data |> 
  pivot_longer(cols = c(16:471), 
               names_to = "partido", 
               values_to = "votos", 
               values_drop_na = TRUE)

eleccion_tidy |> 
  distinct(codigo_distrito_electoral) #Sólo está el 0
# A tibble: 1 × 1
  codigo_distrito_electoral
                      <dbl>
1                         0
Code
eleccion_tidy |> 
  distinct(vuelta) #Sólo vuelta 1 
# A tibble: 1 × 1
  vuelta
   <dbl>
1      1
Code
eleccion_tidy |> 
  distinct(tipo_eleccion) #Sólo tipo 02 --> nacionales
# A tibble: 1 × 1
  tipo_eleccion
  <chr>        
1 02           
Code
eleccion_tidy |> 
  distinct(anno, mes) #Hubo 6 elecciones : 2008,2011,2015,2016,2019 (abril) y 2019 (noviembre)
# A tibble: 6 × 2
   anno mes  
  <dbl> <chr>
1  2008 03   
2  2011 11   
3  2015 12   
4  2016 06   
5  2019 04   
6  2019 11   
Code
#Depuración nombres de partidos

nombres_partidos <- c("PARTIDO SOCIALISTA OBRERO ESPAÑOL","PARTIDO POPULAR", "CIUDADANOS", "PARTIDO NACIONALISTA VASCO", "BLOQUE NACIONALISTA GALLEGO", "UNIDAS PODEMOS - IU", "ESQUERRA REPUBLICANA DE CATALUNYA",  "EH - BILDU", "VOX")

cambia_nombres <- function(partido, nombres) {
  partido_min <- str_to_lower(partido)
  nombres_min <- str_to_lower(nombres)
  
  if (str_detect(partido_min, "\\bsortu\\b|\\beusko alkartasuna\\b|\\baralar\\b|\\balternatiba\\b|\\beuskal herria bildu\\b")) { 
    #Añado el nombre completo de EH - Bildu y cambio a str_detect porque antes no captaba todo lo que debía (ej 2008, Victoria-Gasteiz EZKER BATUA-BERDEAK-ALTERNATIVA)
    return("EH - BILDU")
  }
  
   if (str_detect(partido_min, "\\bunidas podemos\\b|\\bunidos podemos\\b|\\bpodemos\\b|\\biu\\b|\\bpodem\\b|\\bezker batua\\b")) {
    return("UNIDAS PODEMOS - IU")
  }
  
  if (str_detect(partido_min,"\\bpartido nacionalista vasco\\b")) {
    return("PARTIDO NACIONALISTA VASCO")
  }
  
  if (str_detect(partido_min,"\\bpsoe\\b|\\bpartido socialista obrero español\\b\\bpartido socialista de euskadi\\b|\\bpartit dels socialistes de catalunya\\b|\\bpartido dos socialistas de galicia\\b")) {
    return("PARTIDO SOCIALISTA OBRERO ESPAÑOL")
  }
  
    if (str_detect(partido_min,"\\bpp\\b|\\bpartido popular\\b")) {
    return("PARTIDO POPULAR")
    }
  
  if (str_detect(partido_min,"\\bbloque nacionalista galego\\b")) {
    return("BLOQUE NACIONALISTA GALLEGO")  
  }
  
  if (str_detect(partido_min,"\\bpartido de la ciudadanía\\b|\\bpartido de la ciudadania\\b")) {
    return("CIUDADANOS")  
  }
  
  if (str_detect(partido_min,"\\besquerra republicana de catalunya\\b")) { #Nótese que quedan aún partidos tipo coalición (considero que deberían incluirse)
    return("ESQUERRA REPUBLICANA DE CATALUNYA")  
  }
  
  if (any(partido_min == nombres_min)) {
    return(partido)  
  }
  
  return("OTRO")
}

cambia_nombres("PARTIDO MINERO POPULAR", nombres_partidos) #ejemplo
[1] "OTRO"
Code
cambia_nombres("PARTIT POPUPLR-PARTIDO POPULAR", nombres_partidos) #ejemplo
[1] "PARTIDO POPULAR"
Code
cambia_nombres("CIUDADANOS-PARTIDO DE LA CIUDADANÍA", nombres_partidos) #ver que antes no captaba 
[1] "CIUDADANOS"
Code
#Aplicar función al dataframe
eleccion_tidy_filt <- 
  eleccion_tidy |> 
  rowwise() |> 
  mutate(partido_n = cambia_nombres(partido, nombres_partidos))

#Reagrupar partido "otro"
eleccion_resumen <- 
  eleccion_tidy_filt |>
  group_by(partido_n,anno,mes,codigo_ccaa,codigo_provincia,codigo_municipio) |> 
  mutate(votos_totales_partido = sum(votos)) |> 
  ungroup() # Ver anotaciones del cambio
#write_csv(eleccion_resumen, file = "eleccion_resumen.csv") #Tarda un montón en cargar

Encuestas

Debes descartar las encuestas que:

-   se refieran a elecciones anteriores a 2008
-   sean a pie de urna
-   tamaño muestral desconocido o inferior a 500.
-   tenga 1 día o menos de trabajo de campo.
Code
surveys_tidy <- 
  surveys |> 
  pivot_longer(cols = c(11:59), 
               names_to = "partidos", 
               values_to = "intencion_voto", 
               values_drop_na = TRUE) |>
  drop_na(size) |>  
  filter(size >=500 & exit_poll == FALSE) |>   #tamaño muestral y a pie de urna
  filter(date_elec >= "2008-01-01") |>  #elecciones desde 2008
  mutate(duracion_t_campo = field_date_to - field_date_from) |> 
  filter(duracion_t_campo > 1) |> #descartar enucentas con 1 días o menos de trabajo de campo
  select(-exit_poll) |>  #quitar var. a pie de urna porque no es informativa (sólo quedan las que no lo)
  mutate(siglas = case_when(
            partidos == "PSOE" ~ "PSOE",
            partidos == "PP" ~ "PP",
            partidos == "CC" ~ "C's",
            partidos == "BNG" ~ "BNG",
            partidos == "ERC" ~ "ERC",
            partidos == "IU" ~ "PODEMOS-IU",
            partidos == "UP" ~ "PODEMOS-IU",
            partidos == "PODEMOS" ~ "PODEMOS-IU",
            partidos == "EH-BILDU" ~ "EH-BILDU",
            partidos == "EAJ-PNV" ~ "PNV",
            partidos == "VOX" ~ "VOX",
            TRUE ~ "OTRO" ),
         turnout = if_else(is.na(turnout), 0, turnout))

# names(surveys_tidy) <- c("tipo_encuesta", "fecha_elecciones", "id_entrevistador", "entrevistador", "media",
#                          "inicio_trabajo", "final_trabajo", "pie_urna", "n", "participacion_estimada",
#                          "intencion_voto", "duracion_t_campo")
# Por si resulta útil/cómodo más adelante
Code
# Tabla maestra que contiene nombres de municipios, sus códigos y las siglas de cada partido (para facilitar la visualización)

tabla_maestra <-
  eleccion_resumen |> 
  unite(col = "cod_poblacion", codigo_ccaa, codigo_provincia, codigo_municipio, sep = "-", remove = FALSE) |> 
  left_join(cod_mun, by =  c("cod_poblacion" = "cod_mun")) |> 
  mutate(siglas = case_when(
    
    partido_n == "PARTIDO SOCIALISTA OBRERO ESPAÑOL" ~ "PSOE",
    
    partido_n == "PARTIDO POPULAR" ~ "PP",
    
    partido_n == "CIUDADANOS" ~ "C's",
    
    partido_n == "BLOQUE NACIONALISTA GALLEGO" ~ "BNG",
    
    partido_n == "ESQUERRA REPUBLICANA DE CATALUNYA" ~ "ERC",
    
    partido_n == "UNIDAS PODEMOS - IU" ~ "PODEMOS-IU",
    
    partido_n == "EH - BILDU" ~ "EH-BILDU",
    
    partido_n == "PARTIDO NACIONALISTA VASCO" ~ "PNV",
    
    partido_n == "VOX" ~ "VOX",
    
    TRUE ~ "OTRO" ))
Code
# DATOS PREGUNTA 1
datos_p1 <- 
  tabla_maestra |> #Una fila por municipio
  filter(censo > 100000) |> #Condición del censo
  slice_max(votos_totales_partido, by = c(anno, mes, cod_poblacion)) |> #Partido más votado por elección
  distinct(anno, mes, municipio, cod_poblacion, siglas) |>  #Quito filas repetidas (partidos resultantes de la agrupación)
  group_by(anno, mes) |> 
  count(siglas) |> #Por elección cuento nº de veces qeu aparece el partido como más votado (=nº de municipios donde ganó) 
  ungroup() |> 
  mutate(
    siglas = factor(siglas, levels = unique(siglas)), # Aseguramos el orden
    eleccion = case_when(
      anno == 2008 ~ "2008",
      anno == 2011 ~ "2011",
      anno == 2015 ~ "2015",
      anno == 2016 ~ "2016",
      anno == 2019 & mes == "04" ~ 
      "2019 (abril)",
      anno == 2019 & mes == "11" ~ 
        "2019 (noviembre)"
    )
  )

Primera pregunta

¿Qué partido fue el ganador en los municipios con más de 100.000 habitantes (censo) en cada una de las elecciones?

Code
colores_partidos <- c("OTRO" = "grey45", "PP" = "#17589d", "PNV" = "#308444", 
                      "PODEMOS-IU" = "#6b1f5f", "VOX" = "#5ac035", 
                      "PSOE" = "#c20e1a", "ERC" = "#fcc34e", "BNG" = "#76b3dd",
                      "C's" = "#fb5000", "EH-BILDU" = "#1af7db")

ggplot(datos_p1, aes(fill = siglas, values = n)) +
  geom_waffle(n_rows = 10) +
  facet_grid(~eleccion) +
  scale_fill_manual(values = colores_partidos) +
  labs(title = "Partidos ganadores en municipios con >100.000 habitantes",
         fill = "Partido") +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    axis.text = element_blank(),
    strip.text = element_text(face = "bold",
                              size =9),
    plot.title = element_text(face = "bold",
                              hjust = 0.5,
                              margin = margin(b = 10)),
    panel.grid = element_blank())

Segunda pregunta

Code
# DATOS PREGUNTA 2

datos_p2_previo <-
  tabla_maestra |>
  filter(censo > 100000) |> 
  slice_max(votos_totales_partido, by = c(anno, mes, cod_poblacion)) |> 
  distinct(anno, mes, municipio, cod_poblacion, siglas)

# Apartado a: El PSOE es el primer partido

datos_p2_psoe_prim <-
  datos_p2_previo |> 
  filter(siglas == "PSOE")

datos_p2_a <- 
  tabla_maestra |> 
  filter(censo > 100000) |> 
  distinct(anno, mes, municipio, cod_poblacion, siglas, votos_totales_partido) |>
  group_by(anno, mes, cod_poblacion) |> 
  slice_max(votos_totales_partido, n = 2) |> 
  mutate(rank_grupo = rank(-votos_totales_partido)) |> 
  filter(rank_grupo == 2) |> 
  inner_join(datos_p2_psoe_prim, by = c("cod_poblacion", "anno", "mes"), suffix = c("_seg", "_prim")) |> 
  group_by(anno, mes) |> 
  count(siglas_seg) |>
  ungroup() |> 
  mutate(
    siglas = factor(siglas_seg, levels = unique(siglas_seg)), 
    eleccion = case_when(
      anno == 2008 ~ "2008",
      anno == 2011 ~ "2011",
      anno == 2015 ~ "2015",
      anno == 2016 ~ "2016",
      anno == 2019 & mes == "04" ~ 
      "2019 (abril)",
      anno == 2019 & mes == "11" ~ 
        "2019 (noviembre)"
    )
  )

# Gráfico para ver qué partidos son los segundos más votados cuando el PSOE es el primero
ggplot(datos_p2_a, aes(fill = siglas_seg, values = n)) +
  geom_waffle(n_rows = 10) +
  facet_grid(~eleccion) +
  scale_fill_manual(values = colores_partidos) +
  labs(title = "Segundo partido más votado tras el PSOE",
       subtitles = "en municipios con >100.000 habitantes",
         fill = "Partido") +
  theme_minimal() +
  theme(
    legend.position = "right",
    axis.text = element_blank(),
    strip.text = element_text(face = "bold",
                              size =9),
    plot.title = element_text(face = "bold",
                              hjust = 0.5,
                              margin = margin(b = 10)),
    panel.grid = element_blank())
Code
# DATOS PREGUNTA 2
# Apartado b: El PP es el primer partido

datos_p2_pp_prim <-
  datos_p2_previo |> 
  filter(siglas == "PP")


datos_p2_b <- 
  tabla_maestra |> 
  filter(censo > 100000) |> 
  distinct(anno, mes, municipio, cod_poblacion, siglas, votos_totales_partido) |>
  group_by(anno, mes, cod_poblacion) |> 
  slice_max(votos_totales_partido, n = 2) |> 
  mutate(rank_grupo = rank(-votos_totales_partido)) |> 
  filter(rank_grupo == 2) |> 
  inner_join(datos_p2_pp_prim, by = c("cod_poblacion", "anno", "mes"), suffix = c("_seg", "_prim")) |> 
  group_by(anno, mes) |> 
  count(siglas_seg) |>
  ungroup() |> 
  mutate(
    siglas = factor(siglas_seg, levels = unique(siglas_seg)), 
    eleccion = case_when(
      anno == 2008 ~ "2008",
      anno == 2011 ~ "2011",
      anno == 2015 ~ "2015",
      anno == 2016 ~ "2016",
      anno == 2019 & mes == "04" ~ 
      "2019 (abril)",
      anno == 2019 & mes == "11" ~ 
        "2019 (noviembre)"
    )
  )

# Gráfico para ver qué partidos son los segundos más votados cuando el PSOE es el primero
ggplot(datos_p2_b, aes(fill = siglas_seg, values = n)) +
  geom_waffle(n_rows = 10) +
  facet_grid(~eleccion) +
  scale_fill_manual(values = colores_partidos) +
  labs(title = "Segundo partido más votado tras el PP",
       subtitle = "en municipios con >100.000 habitantes",
         fill = "Partido") +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    axis.text = element_blank(),
    strip.text = element_text(face = "bold",
                              size =9),
    plot.title = element_text(face = "bold",
                              hjust = 0.5,
                              margin = margin(b = 10)),
    panel.grid = element_blank())

Tercera pregunta

¿Cómo calibrar el error de las encuestas (recordemos que las encuestas son de intención de voto a nivel nacional)?

Resultados de las elecciones:

Code
# Preparamos los resultados de las elecciones, vemos qué porcentaje de votos ha ido a cada partido

datos_generales_elecciones <- 
  tabla_maestra |>
  group_by(anno,mes) |> 
  distinct(anno, mes, cod_poblacion, codigo_ccaa, codigo_provincia, codigo_municipio, codigo_distrito_electoral, censo, votos_blancos, votos_nulos, votos_candidaturas) |> 
  mutate(censo = sum(censo),
         votos_blancos = sum(votos_blancos),
         votos_nulos = sum(votos_nulos),
         votos_candidaturas = sum(votos_candidaturas),
         eleccion = case_when(
            anno == 2008 ~ "2008",
            anno == 2011 ~ "2011",
            anno == 2015 ~ "2015",
            anno == 2016 ~ "2016",
            anno == 2019 & mes == "04" ~ 
            "2019 (abril)",
            anno == 2019 & mes == "11" ~ 
              "2019 (noviembre)")) |> 
  ungroup() |> 
  distinct(eleccion, censo, votos_blancos, votos_nulos, votos_candidaturas) 

datos_partido <-
  tabla_maestra |> 
  group_by(anno, mes, siglas) |> 
  mutate(votos_partido = sum(votos),
         eleccion = case_when(
            anno == 2008 ~ "2008",
            anno == 2011 ~ "2011",
            anno == 2015 ~ "2015",
            anno == 2016 ~ "2016",
            anno == 2019 & mes == "04" ~ 
            "2019 (abril)",
            anno == 2019 & mes == "11" ~ 
              "2019 (noviembre)")) |> 
  ungroup() |> 
  distinct(eleccion, siglas, votos_partido) |> 
  left_join(datos_generales_elecciones, by = c("eleccion" = "eleccion")) |> 
  mutate(votos_porc_votantes_cand = round(votos_partido / votos_candidaturas, 2), # Porcentaje sobre la gente que voto candidaturas
         votos_porc_censo = round(votos_partido / censo, 2)) # Porcentaje sobre la gente censada,

datos_partido <-
  datos_partido |> 
  mutate(siglas = factor(siglas, levels = c("PP","PSOE","PNV","OTRO","ERC","BNG","PODEMOS-IU","C's","EH-BILDU","VOX"), 
                         ordered = TRUE)) 


grafico_resultados_elecciones <- 
  ggplot(datos_partido, aes(x = eleccion, y = votos_porc_votantes_cand, fill = siglas)) +
  geom_col(position = "fill") +
    geom_text(
    aes(
      label = ifelse(votos_porc_votantes_cand > 0.08, scales::percent(votos_porc_votantes_cand, accuracy = 1), ""),
      y = votos_porc_votantes_cand / 2
    ),
    position = position_fill(vjust = 0.5),
    size = 3,
    color = "white"
  ) +
  scale_fill_manual(values = colores_partidos) +
  labs(
    x = "Elecciones",
    y = "Porcentaje de votos",
    fill = "Partido"
  ) +
  theme_minimal()
grafico_resultados_elecciones

Podemos ver que los resultados de las encuestas se suelen desviar entre cero con algo y 2 puntos porcentuales

Code
# Preparamos los datos de las encuestas, vemos qué porcentaje de votantes se estiman para cada partido
head(surveys_tidy)
# A tibble: 6 × 13
  type_survey date_elec  id_pollster pollster media              field_date_from
  <chr>       <date>     <chr>       <chr>    <chr>              <date>         
1 national    2008-03-09 pollster-49 GESOP    EL PERIÓDIC ANDOR… 2008-03-05     
2 national    2008-03-09 pollster-49 GESOP    EL PERIÓDIC ANDOR… 2008-03-05     
3 national    2008-03-09 pollster-49 GESOP    EL PERIÓDIC ANDOR… 2008-03-05     
4 national    2008-03-09 pollster-49 GESOP    EL PERIÓDIC ANDOR… 2008-03-05     
5 national    2008-03-09 pollster-49 GESOP    EL PERIÓDIC ANDOR… 2008-03-05     
6 national    2008-03-09 pollster-49 GESOP    EL PERIÓDIC ANDOR… 2008-03-05     
# ℹ 7 more variables: field_date_to <date>, size <dbl>, turnout <dbl>,
#   partidos <chr>, intencion_voto <dbl>, duracion_t_campo <drtn>, siglas <chr>
Code
surveys_general <-
  surveys_tidy |> 
  distinct(date_elec, pollster, field_date_from, field_date_to, size, turnout) |> 
  mutate(personas_turnout = round((size * turnout)/100),0) |> 
  group_by(date_elec, pollster) |> 
  mutate(size = sum(size),
         personas_turnout = sum(personas_turnout, na.rm = TRUE),
         eleccion =  case_when(
            year(date_elec) == 2008 ~ "2008",
            year(date_elec)  == 2011 ~ "2011",
            year(date_elec)  == 2015 ~ "2015",
            year(date_elec)  == 2016 ~ "2016",
            year(date_elec)  == 2019 & month(date_elec)  == "4" ~ 
            "2019 (abril)",
            year(date_elec)  == 2019 &  month(date_elec) == "11" ~ 
              "2019 (noviembre)")) |> 
  distinct(eleccion, pollster, size, personas_turnout)
  
surveys_partido <-
  surveys_tidy |> 
  mutate(votantes = round(((size - turnout)*intencion_voto)/100, 0)) |> 
  group_by(date_elec, pollster, siglas) |> 
  mutate(votantes_estimados = sum(votantes, na.rm = TRUE)) |> 
  distinct(date_elec, pollster, siglas, votantes_estimados) |> 
  left_join(surveys_general, by = c("date_elec" = "date_elec", "pollster" = "pollster")) |> 
  mutate(votos_porc_votantes_cand = round(votantes_estimados / (size - personas_turnout), 2),
         votos_porc_censo = round(votantes_estimados / size, 2),
         eleccion =  case_when(
            year(date_elec) == 2008 ~ "2008",
            year(date_elec)  == 2011 ~ "2011",
            year(date_elec)  == 2015 ~ "2015",
            year(date_elec)  == 2016 ~ "2016",
            year(date_elec)  == 2019 & month(date_elec)  == "4" ~ 
            "2019 (abril)",
            year(date_elec)  == 2019 &  month(date_elec) == "11" ~ 
              "2019 (noviembre)"))  |> 
  group_by(eleccion, siglas) |> 
  mutate(media_porc_encuesta = mean(votos_porc_votantes_cand)) |> 
  ungroup()

# Comparamos los datos reales vs los de las encuestas

comparacion <- 
  left_join(x = surveys_partido, y = datos_partido, by = c("eleccion" = "eleccion", "siglas" = "siglas")) |> 
  select (eleccion, pollster, siglas, votos_porc_votantes_cand.x, votos_porc_votantes_cand.y, votos_porc_censo.x, votos_porc_censo.y) |> 
  mutate(error_relativo_cand = abs(votos_porc_votantes_cand.y - votos_porc_votantes_cand.x) / votos_porc_votantes_cand.y,
         error_relativo_censo = abs(votos_porc_censo.y - votos_porc_censo.x) / votos_porc_censo.y,
         error_real = (votos_porc_votantes_cand.x - votos_porc_votantes_cand.y) / votos_porc_votantes_cand.y ,
         error_positivo_negativo = case_when (error_real >=0 ~ "Positivo", TRUE ~ "Negativo")) |> 
  drop_na(eleccion)
# Propuesta 0 : caja y bigotes

grafico_comparacion_partido <-
  ggplot(comparacion, aes(x = error_relativo_cand, y = siglas, fill = siglas)) +
  geom_boxplot() +
  facet_wrap(~eleccion) +
  scale_fill_manual(values = colores_partidos)  +
    labs(
    x = "Error absoluto relativo",
    y = "Partido",
    fill = "Partido"
  ) +
  guides(fill = "none")
grafico_comparacion_partido

Code
# Propuesta 1 : barras

error_positivo_negativo <-
  comparacion |> 
  group_by(pollster) |> 
  count(error_positivo_negativo) |> 
  mutate(totales = sum(n),
         porc = round(n / totales,1))

orden_pollsters <-
  error_positivo_negativo |> 
  filter(error_positivo_negativo == "Negativo") |> 
  arrange(-porc) |> 
  select(pollster) |> 
  pull()

error_positivo_negativo <-
  error_positivo_negativo |> 
  mutate(pollster = factor(pollster, levels = orden_pollsters, ordered= TRUE))

ggplot(error_positivo_negativo) + 
  geom_col(aes( y = pollster, x = porc, fill = error_positivo_negativo)) +
    theme(axis.text.y = element_text(size = 7))

Code
# Propuesta 2 : lollipop

# Partido que ganó las elecciones
datos_partido_ganador <- 
  datos_partido |> 
  group_by(eleccion) |> 
  slice_max(votos_partido)

comparacion_filtro <- 
  comparacion |> 
  inner_join(y = datos_partido_ganador, by = c("eleccion" = "eleccion", "siglas" = "siglas")) |> 
  filter(eleccion == "2019 (noviembre)") |> 
  select(eleccion, pollster, error_real)

orden_pollsters2 <-
  comparacion_filtro |> 
  arrange(- error_real) |> 
  select(pollster) |> 
  pull()

comparacion_filtro <-
  comparacion_filtro |> 
  mutate(pollster = factor(pollster, levels = orden_pollsters2, ordered = TRUE))
  
ggplot(comparacion_filtro, aes(x = pollster, y = error_real)) +
  geom_segment( aes(x = pollster, xend = pollster, y=0, yend = error_real), color="grey", size = 1.2) +
  geom_point( color="orange", size = 4) +
  facet_wrap(~ eleccion) +
  theme_light() +
  theme(
    panel.grid.major.x = element_blank(),
    panel.border = element_blank(),
    axis.ticks.x = element_blank(),
    axis.text.x = element_text(angle = 90)
  ) +
  xlab("") +
  ylab("Desviación porc. de los votos reales") +
  coord_flip()

Code
# Propuesta 3: lollipop por años con el promedio

comparacion_filtro3 <- 
  comparacion |> 
  inner_join(y = datos_partido_ganador, by = c("eleccion" = "eleccion", "siglas" = "siglas")) |>
  group_by(eleccion) |> 
  mutate(promedio_error = mean(error_real)) |> 
  distinct(eleccion, promedio_error)


ggplot(comparacion_filtro3, aes(x = eleccion, y = promedio_error)) +
  geom_segment( aes(x = eleccion, xend = eleccion, y=0, yend = promedio_error), color="grey", size = 1.2) +
  geom_point( color="orange", size = 4) +
  theme_light() +
  theme(
    panel.grid.major.x = element_blank(),
    panel.border = element_blank(),
    axis.ticks.x = element_blank(),
    axis.text.x = element_text(angle = 90)
  ) +
  xlab("") +
  ylab("Desviación porc. de los votos reales") +
  coord_flip()

Parece que hay algunas empresas encuestadoras que se desvían más que otras, ver cómo poner este gráfico por años

Code
# Propuesta 4: cajas y bigotes por encuestadora
grafico_comparacion_pollster <-
  comparacion |> 
  filter(eleccion == "2015") |> 
  ggplot( aes(x = error_relativo_cand, y = pollster, fill = pollster)) +
  geom_boxplot() +
  labs(
    x = "Error absoluto relativo",
    y = "Encuestadora",
    fill = "Encuestadora"
  ) +
  guides(fill = "none") +
  facet_wrap(~eleccion) 
grafico_comparacion_pollster
Code
# Preparación para ráfico escaños

datos_elecciones_provincia <- 
  tabla_maestra |>
  group_by(anno, mes, codigo_provincia) |> 
  distinct(anno, mes, codigo_provincia, votos_blancos, votos_candidaturas) |> 
  mutate(votos_blancos = sum(votos_blancos),
         votos_candidaturas = sum(votos_candidaturas),
         eleccion = case_when(
            anno == 2008 ~ "2008",
            anno == 2011 ~ "2011",
            anno == 2015 ~ "2015",
            anno == 2016 ~ "2016",
            anno == 2019 & mes == "04" ~ 
            "2019 (abril)",
            anno == 2019 & mes == "11" ~ 
              "2019 (noviembre)")) |> 
  ungroup() |> 
  distinct(eleccion, codigo_provincia, votos_blancos, votos_candidaturas) 

datos_partido_provincia <-
  tabla_maestra |> 
  group_by(anno, mes, codigo_provincia,  partido) |> 
  mutate(votos_partido = sum(votos),
         eleccion = case_when(
            anno == 2008 ~ "2008",
            anno == 2011 ~ "2011",
            anno == 2015 ~ "2015",
            anno == 2016 ~ "2016",
            anno == 2019 & mes == "04" ~ 
            "2019 (abril)",
            anno == 2019 & mes == "11" ~ 
              "2019 (noviembre)")) |> 
  ungroup() |> 
  distinct(anno, eleccion, codigo_provincia, partido, votos_partido) 
  #left_join(datos_elecciones_provincia, by = c("eleccion" = "eleccion", "codigo_provincia" = "codigo_provincia")) |> 
  #mutate(porc_votos_validos = round(votos_partido / (votos_candidaturas + votos_blancos), 2)) # % votos de la provincia
  #filter(porc_votos_validos >= 0.03)   # Para participar en D'Hondt 


# datos_partido_provincia |> 
#   group_by(eleccion, partido) |> 
#   summarise(suma = sum(votos_partido)) |> 
#   ungroup() |> 
#   write.csv(file="votos_partidos.csv")



# Importamos el número de escaños por provincia y año

library(readr)
escannos_provincia_anno <- read_csv("data/escannos_provincia_anno.csv")

escannos_provincia_anno <-
  escannos_provincia_anno |> 
  mutate(codigo_provincia = as.character(case_when(
          Provincia == "Madrid" ~ "28",
          Provincia == "Barcelona" ~ "08",
          Provincia == "Valencia" ~ "46",
          Provincia == "Sevilla" ~ "41",
          Provincia == "Alicante" ~ "03",
          Provincia == "Málaga" ~ "29",
          Provincia == "Murcia" ~ "30",
          Provincia == "Cádiz" ~ "11",
          Provincia == "Baleares" ~ "07",
          Provincia == "La Coruña" ~ "15",
          Provincia == "Las Palmas" ~ "35",
          Provincia == "Asturias" ~ "33",
          Provincia == "Granada" ~ "18",
          Provincia == "Pontevedra" ~ "36",
          Provincia == "Santa Cruz de Tenerife" ~ "38",
          Provincia == "Zaragoza" ~ "50",              
          Provincia == "Almería" ~ "04",
          Provincia == "Córdoba" ~ "14",
          Provincia == "Gerona" ~ "17",
          Provincia == "Guipúzcoa" ~ "20",
          Provincia == "Tarragona" ~ "43",
          Provincia == "Toledo" ~ "45",
          Provincia == "Badajoz" ~ "06",
          Provincia == "Cantabria" ~ "39",
          Provincia == "Castellón" ~ "12",
          Provincia == "Ciudad Real" ~ "13",
          Provincia == "Huelva" ~ "21",
          Provincia == "Jaén" ~ "23",
          Provincia == "Navarra" ~ "31",
          Provincia == "Valladolid"  ~ "47",
          Provincia == "Álava" ~ "01",
          Provincia == "Albacete" ~ "02",
          Provincia == "Burgos" ~ "09",
          Provincia == "Cáceres" ~ "10",
          Provincia == "León" ~ "24",
          Provincia == "Lérida"  ~ "25",
          Provincia == "Lugo" ~ "27",
          Provincia == "Orense" ~ "32",
          Provincia == "La Rioja" ~ "26",
          Provincia == "Salamanca"  ~ "37",
          Provincia == "Ávila" ~ "05",
          Provincia == "Cuenca" ~ "16",
          Provincia == "Guadalajara" ~ "19",
          Provincia == "Huesca"  ~ "22",
          Provincia == "Palencia"  ~ "34",
          Provincia == "Segovia" ~ "40",
          Provincia == "Teruel" ~ "44",
          Provincia == "Vizcaya" ~ "48",
          Provincia == "Zamora" ~ "49",
          Provincia == "Soria" ~ "42",
          Provincia == "Ceuta" ~ "51",
          Provincia == "Melilla" ~ "52"))) |> 
  distinct() 


datos_provincia_escannos <-
  datos_partido_provincia |> 
  left_join(escannos_provincia_anno, by = c("anno" = "Año", "codigo_provincia" = "codigo_provincia")) |> 
  select(eleccion, codigo_provincia, partido, votos_partido, "Número de escaños")

## Función D'Hondt
dHondt <- function(votos, partidos, escaños) {
  
  # Formato tibble
  tabla <- tibble(partido = partidos, votos = votos)
  
  # Divisores
  divisores <- rep(1, length(votos))
  escaños_asignados <- integer(length(votos))
  
  # Tenemos que repetir el proceso por escaños
  for (i in 1:escaños) {
    # Máximo cociente
    cocientes <- votos / divisores
    max_index <- which.max(cocientes)
    escaños_asignados[max_index] <- escaños_asignados[max_index] + 1
    divisores[max_index] <- divisores[max_index] + 1
  }
  
  # Resultado final
  resultado <- tibble(
    partido = partidos,
    escaños = escaños_asignados
  )
  
  return(resultado)
}


## Función DHondt por provincias

dHondt_provincias <- function(tibble) {
  
  # Inicializamos los resultados
  resultados_dhondt <- tibble()
  
  # Por cada elección de las que tenemos
  for (elec in unique(tibble$eleccion)) {
    # Filtrar por elección actual
    tibble_funcion <- 
      tibble |> 
      filter(eleccion == elec)
    
    # Por cada provincia, ya que cada una tiene unos escaños
    for (provin in unique(tibble_funcion$codigo_provincia)) {
      # Filtrar por provincia actual
      tibble_funcion2 <- 
        tibble_funcion |> 
        filter(codigo_provincia == provin)
      
      # Aplicamos la función de antes
      resultados <- 
        dHondt(
        votos = tibble_funcion2$votos_partido, 
        partidos = tibble_funcion2$partido, 
        escaños = unique(tibble_funcion2$`Número de escaños`)
      )
      
      # Añadimos qué elección es y provincia
      resultados <- 
        resultados |> 
        mutate(eleccion = elec, 
               codigo_provincia = provin)
      
      # Añadimos a la inicialización
      resultados_dhondt <- bind_rows(resultados_dhondt, resultados)
    }
  }
  
  return(resultados_dhondt)
}

resultado_dhondt <-
  dHondt_provincias(datos_provincia_escannos) 
# |> 
#   group_by(eleccion, partido) |> 
#   summarise(sum(escaños)) |> 
#   write.csv(file = "escaños_partidos.csv")


congreso <- 
  resultado_dhondt |> 
  rowwise() |> 
  mutate(partido = cambia_nombres(partido, nombres = nombres_partidos)) |>
  ungroup() |> 
  mutate(siglas = case_when(
            partido == "PARTIDO SOCIALISTA OBRERO ESPAÑOL" ~ "PSOE",
            partido == "PARTIDO POPULAR" ~ "PP",
            partido == "CIUDADANOS" ~ "C's",
            partido == "BLOQUE NACIONALISTA GALLEGO" ~ "BNG",
            partido == "ESQUERRA REPUBLICANA DE CATALUNYA" ~ "ERC",
            partido == "UNIDAS PODEMOS - IU" ~ "PODEMOS-IU",
            partido == "EH - BILDU" ~ "EH-BILDU",
            partido == "PARTIDO NACIONALISTA VASCO" ~ "PNV",
            partido == "VOX" ~ "VOX",
            TRUE ~ "OTRO" )) |> 
   group_by(siglas, eleccion) |> 
   summarise(escannos = sum(escaños)) |> 
     ungroup() #|> 
  #arrange(eleccion, escannos)

congreso <- 
  congreso |> 
  mutate(siglas = factor(siglas, 
                         levels = unique(congreso$siglas), 
                         labels = c("BNG", "C's", "EH-BILDU", "ERC", "OTRO", "PNV", "PODEMOS-IU", "PP", "PSOE", "VOX"), 
                         ordered = TRUE)) 



unique(congreso$eleccion)
[1] "2008"             "2011"             "2019 (abril)"     "2019 (noviembre)"
[5] "2015"             "2016"            
Code
## Gráfico de congreso

library(ggpol)
library(ggforce)

# Tenemos que filtar por años, porque la geometria geom_parliament() da problemas
# con las leyends de colores/relleno con los facet wrap si los niveles de las 
# leyendas no son exactamente los mismos siempre.

# 2008 #

congreso_2008 <-
congreso |> 
           filter(eleccion == "2008")

# congreso_2008 |> 
#   group_by(siglas) |> 
#   summarise(escannos) |> 
#   arrange(escannos)

colores_2008 <- c(
  "8" = "#17589d", # PP
  "9" = "#c20e1a", # SOE
  "6" = "#308444", # PNV 
  "5" = "#808080", # OTRO 
  "7" = "#308444", # PNV
  "10" = "#308444", # PNV
  "4" = "#FFD700", #ERC
  "3" = "#76b3dd",
  "1" = "#76b3dd"
  )

congreso_2008_g <- 
  ggplot(congreso_2008)+
  geom_parliament(
    aes(
      seats = escannos, 
      fill = siglas,
      color = siglas)) +
  scale_fill_manual(values = colores_2008) +
  scale_color_manual(values = colores_2008) +
  guides(color = "none", fill = "none") +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white", color = NA)) +
  coord_fixed()
  

congreso_2008_t <-
  congreso_2008 |> 
  filter(eleccion == "2008" ) |> 
  select(siglas, escannos) |> 
  arrange(- escannos) |> 
  filter(escannos > 0)

congreso_2008_tg <- 
  ggplot(congreso_2008_t, aes(x = 1, y = reorder(siglas, escannos), label = paste(siglas, escannos))) +
  geom_text(aes(color = siglas), size = 3.5) + # Añadir texto con colores
  scale_color_manual(values = colores_partidos) + # Usa los colores definidos en la tabla
  theme_minimal() +
  guides(color = "none") +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank()
  )

library(gridExtra)
library(grid)

grafico_congreso1 <- grid.arrange(congreso_2008_g, congreso_2008_tg, ncol = 2,
             top = textGrob("2008", gp = gpar(fontsize = 12, fontface = "bold") 
  ))
Code
# 2011 #

congreso_2011 <-
congreso |> 
           filter(eleccion == "2011")

# congreso_2011 |> 
#   group_by(siglas) |> 
#   summarise(escannos) |> 
#   arrange(escannos)

colores_2011 <- c(
  "6" = "#17589d", # PP
  "7" = "#c20e1a", # SOE
  "5" = "#308444", # PNV
  "4" = "#308444", # PNV 
  "3" = "#808080", # OTRO 
  "2" = "#fcc34e", # ERC
  "1" = "#76b3dd" #BNG
)

congreso_2011_g <- 
  ggplot(congreso_2011)+
  geom_parliament(
    aes(
      seats = escannos, 
      fill = siglas,
      color = siglas)) +
  scale_fill_manual(values = colores_2011) +
  scale_color_manual(values = colores_2011) +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white", color = NA)) +
  guides(color = "none", fill = "none") +
  coord_fixed()
  

congreso_2011_t <-
  congreso_2011 |> 
  filter(eleccion == "2011" ) |> 
  select(siglas, escannos) |> 
  arrange(- escannos) |> 
  filter(escannos > 0)

congreso_2011_tg <- 
  ggplot(congreso_2011_t, aes(x = 1, y = reorder(siglas, escannos), label = paste(siglas, escannos))) +
  geom_text(aes(color = siglas), size = 3.5) + # Añadir texto con colores
  scale_color_manual(values = colores_partidos) + # Usa los colores definidos en la tabla
  theme_minimal() +
  guides(color = "none") +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank()
  )

grafico_congreso2 <- grid.arrange(congreso_2011_g, congreso_2011_tg, ncol = 2,
             top = textGrob("2011", gp = gpar(fontsize = 12, fontface = "bold") ))
Code
# 2015 #

congreso_2015 <-
congreso |> 
           filter(eleccion == "2015")
# 
# congreso_2015 |> 
#   group_by(siglas) |> 
#   summarise(escannos) |> 
#   arrange(escannos)

colores_2015 <- c(
  "7" = "#17589d", # PP
  "8" = "#c20e1a", # SOE
  "9" = "#c20e1a", # SOE
  "6" = "#6b1f5f", # Podemos
  "1" = "#fb5000", # Cs
  "4" = "#808080", # OTRO 
  "3" = "#fcc34e", # ERC
  "2" = "#1af7db", # PNV 
  "5" = "#006400" #BILDU
)

congreso_2015_g <- 
  ggplot(congreso_2015)+
  geom_parliament(
    aes(
      seats = escannos, 
      fill = siglas,
      color = siglas)) +
  scale_fill_manual(values = colores_2015) +
  scale_color_manual(values = colores_2015) +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white", color = NA)) +
  guides(color = "none", fill = "none") +
  coord_fixed()
  


congreso_2015_t <-
  congreso_2015 |> 
  filter(eleccion == "2015" ) |> 
  select(siglas, escannos) |> 
  arrange(- escannos) |> 
  filter(escannos > 0)

congreso_2015_tg <- 
  ggplot(congreso_2015_t, aes(x = 1, y = reorder(siglas, escannos), label = paste(siglas, escannos))) +
  geom_text(aes(color = siglas), size = 3.5) + # Añadir texto con colores
  scale_color_manual(values = colores_partidos) + # Usa los colores definidos en la tabla
  theme_minimal() +
  guides(color = "none") +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank()
  )

grafico_congreso3 <- grid.arrange(congreso_2015_g, congreso_2015_tg, ncol = 2,
             top = textGrob("2015", gp = gpar(fontsize = 12, fontface = "bold") 
  ))
Code
# 2016 #

congreso_2016 <-
congreso |> 
           filter(eleccion == "2016")

# congreso_2016 |> 
#   group_by(siglas) |> 
#   summarise(escannos) |> 
#   arrange(escannos)

colores_2016 <- c(
  "6" = "#17589d", # PP
  "7" = "#c20e1a", # SOE
  "8" = "#c20e1a", # SOE, lo repito porque se quedaba un punto gris
  "5" = "#6b1f5f", # Podemos
  "3" = "#fb5000", # Cs
  "1" = "#808080", # OTRO 
  "4" = "#308444", # PNV 
  "2" = "#1af7db" #BILDU
)

congreso_2016_g <- 
  ggplot(congreso_2016)+
  geom_parliament(
    aes(
      seats = escannos, 
      fill = siglas,
      color = siglas)) +
  scale_fill_manual(values = colores_2016) +
  scale_color_manual(values = colores_2016) +
  guides(color = "none", fill = "none") +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white", color = NA)) +
  coord_fixed()
  


congreso_2016_t <-
  congreso_2016 |> 
  filter(eleccion == "2016" ) |> 
  select(siglas, escannos) |> 
  arrange(- escannos) |> 
  filter(escannos > 0)

congreso_2016_tg <- 
  ggplot(congreso_2016_t, aes(x = 1, y = reorder(siglas, escannos), label = paste(siglas, escannos))) +
  geom_text(aes(color = siglas), size = 3.5) + # Añadir texto con colores
  scale_color_manual(values = colores_partidos) + # Usa los colores definidos en la tabla
  theme_minimal() +
  guides(color = "none") +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank()
  )

grafico_congreso4 <- grid.arrange(congreso_2016_g, congreso_2016_tg, ncol = 2,
             top = textGrob("2016", gp = gpar(fontsize = 12, fontface = "bold") ))
Code
# "2019 (abril)"  #

congreso_2019a <-
congreso |> 
           filter(eleccion == "2019 (abril)" )

# congreso_2019a |> 
#   group_by(siglas) |> 
#   summarise(escannos) |> 
#   arrange(escannos)

colores_2019a <- c(
  "8" = "#17589d", # PP
  "9" = "#c20e1a", # SOE
  "7" = "#6b1f5f", # Podemos
  "2" = "#fb5000", # Cs
  "5" = "#808080", # OTRO 
  "6" = "#308444", # PNV 
  "3" = "#1af7db", #BILDU
  "10" = "#5ac035", #VOX
  "4" = "#fcc34e" # ERC
)

congreso_2019a_g <- 
  ggplot(congreso_2019a)+
  geom_parliament(
    aes(
      seats = escannos, 
      fill = siglas,
      color = siglas)) +
  scale_fill_manual(values = colores_2019a) +
  scale_color_manual(values = colores_2019a) +
  guides(color = "none", fill = "none") +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white", color = NA))+
  coord_fixed()
  

congreso_2019a_t <-
  congreso_2019a |> 
  filter(eleccion == "2019 (abril)" ) |> 
  select(siglas, escannos) |> 
  arrange(- escannos) |> 
  filter(escannos > 0)

congreso_2019a_tg <- 
  ggplot(congreso_2019a_t, aes(x = 1, y = reorder(siglas, escannos), label = paste(siglas, escannos))) +
  geom_text(aes(color = siglas), size = 3) + # Añadir texto con colores
  scale_color_manual(values = colores_partidos) + # Usa los colores definidos en la tabla
  theme_minimal() +
  guides(color = "none") +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank()
  )

grafico_congreso5 <- grid.arrange(congreso_2019a_g, congreso_2019a_tg, ncol = 2,
             top = textGrob("2019 abril", gp = gpar(fontsize = 12, fontface = "bold")  ))
Code
# "2019 (noviembre)"  #

congreso_2019n <-
congreso |> 
           filter(eleccion == "2019 (noviembre)" )

# congreso_2019n |> 
#   group_by(siglas) |> 
#   summarise(escannos) |> 
#   arrange(escannos)

colores_2019n <- c(
  "8" = "#17589d", # PP
  "9" = "#c20e1a", # SOE
  "7" = "#6b1f5f", # Podemos
  "2" = "#fb5000", # Cs
  "5" = "#808080", # OTRO 
  "6" = "#308444", # PNV 
  "3" = "#1af7db", #BILDU
  "10" = "#5ac035", #VOX
  "4" = "#fcc34e", # ERC
  "1" = "#76b3dd" #BNG
)

congreso_2019n_g <- 
  ggplot(congreso_2019n)+
  geom_parliament(
    aes(
      seats = escannos, 
      fill = siglas,
      color = siglas)) +
  scale_fill_manual(values = colores_2019n) +
  scale_color_manual(values = colores_2019n) +
  guides(color = "none", fill = "none") +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white", color = NA)) +
  coord_fixed()
  
congreso_2019n_t <-
  congreso_2019n |> 
  filter(eleccion == "2019 (noviembre)" ) |> 
  select(siglas, escannos) |> 
  arrange(- escannos)

congreso_2019n_tg <- 
  ggplot(congreso_2019n_t, aes(x = 1, y = reorder(siglas, escannos), label = paste(siglas, escannos))) +
  geom_text(aes(color = siglas), size = 3) + # Añadir texto con colores
  scale_color_manual(values = colores_partidos) + # Usa los colores definidos en la tabla
  theme_minimal() +
  guides(color = "none") +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank()
  )

grafico_congreso6 <- grid.arrange(congreso_2019n_g, congreso_2019n_tg, ncol = 2,
             top = textGrob("2019 noviembre", gp = gpar(fontsize = 12, fontface = "bold") ))
Code
grid.arrange(grafico_congreso1, grafico_congreso2, grafico_congreso3, grafico_congreso4, grafico_congreso5, grafico_congreso6, ncol = 2, nrow = 3)
Reading layer `Provincias_ETRS89_30N' from data source 
  `C:\Users\elisa\Downloads\software-rama_eli\software-rama_eli\data\Provincias_ETRS89_30N.shp' 
  using driver `ESRI Shapefile'
Simple feature collection with 52 features and 5 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -1004502 ymin: 3132137 xmax: 1126932 ymax: 4859240
Projected CRS: ETRS89 / UTM zone 30N
Simple feature collection with 6 features and 10 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: 121464.4 ymin: 4059438 xmax: 781036.7 ymax: 4784875
Projected CRS: ETRS89 / UTM zone 30N
  Codigo    Texto Texto_Alt Cod_CCAA                 CCAA eleccion     siglas
1     01    Álava     Araba       16           País Vasco     2015 PODEMOS-IU
2     02 Albacete  Albacete       08 Castilla - La Mancha     2015         PP
3     03 Alicante   Alacant       10 Comunitat Valenciana     2015         PP
4     04  Almería   Almería       01            Andalucía     2015         PP
5     05    Ávila     Ávila       07      Castilla y León     2015         PP
6     06  Badajoz   Badajoz       11          Extremadura     2015       PSOE
  votos_partido votos_totales      porc                       geometry
1         48266        177448 0.2720008 MULTIPOLYGON (((497823.7 47...
2         85152        229154 0.3715929 MULTIPOLYGON (((630529.3 43...
3        296709        897466 0.3306075 MULTIPOLYGON (((720290.8 42...
4        117407        306446 0.3831246 MULTIPOLYGON (((572241.6 40...
5         46963        100859 0.4656302 MULTIPOLYGON (((331047.9 45...
6        148347        395612 0.3749810 MULTIPOLYGON (((355598.1 43...
grafico_pais